package com.mfz.common.encryption.rsa

import java.nio.file.Files
import java.nio.file.Paths
import java.security.Key
import java.security.KeyFactory
import java.security.interfaces.RSAPrivateKey
import java.security.spec.PKCS8EncodedKeySpec
import java.util.*

/**
 *
 * create by 2019-06-19.
 * @author yimin
 */

class RsaClient(bytes: ByteArray) : AbstractRsa() {
	override val key: Key
	override val keyLength: Int

	init {
		try {
			//通过PKCS#8编码的Key指令获得私钥对象
			val spec = PKCS8EncodedKeySpec(bytes)
			val kf = KeyFactory.getInstance(RSA_ALGORITHM)
			this.key   = kf.generatePrivate(spec) as RSAPrivateKey
			keyLength = key.modulus.bitLength()
		} catch (e: Exception) {
			throw RuntimeException("不支持的密钥", e)
		}
	}
}

/**
 * 从一个二进制文件当中读取客户端的密钥
 */
fun getRsaClientByFile(fileName: String): RsaClient {
	val kBytes = Files.readAllBytes(Paths.get(fileName))
	return RsaClient(kBytes)
}

/**
 * 从一个Base64字符串流当中当中读取客户端的密钥
 */
fun getRsaClientByBase64(base64Code: String): RsaClient {
	return RsaClient(Base64.getDecoder().decode(base64Code))
}